package com.bugbuff.dubbo.server.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.bugbuff.common.pojo.User;
import com.bugbuff.common.pojo.UserInfo;
import com.bugbuff.common.service.PicUploadService;
import com.bugbuff.common.utils.UserThreadLocal;
import com.bugbuff.common.vo.PicUploadResult;
import com.bugbuff.dubbo.server.api.VoiceApi;
import com.bugbuff.dubbo.server.pojo.Voice;
import com.bugbuff.dubbo.server.vo.VoiceVo;
import lombok.extern.slf4j.Slf4j;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

@Service
@Slf4j
public class TaoHuaService {

    //用户获取语音剩余次数数据存储在Redis中key的前缀
    private static final String REMANNING_REDIS_KEY_PREFIX = "REMANNING_TIME_";

    //用户获取过的语音vid对应的key的前缀
    private static final String VOICE_REDIS_KEY_PREFIX = "VOICE_RECEIVED_";

    @Autowired
    private PicUploadService picUploadService;

    @Reference
    private VoiceApi voiceApi;

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 发送语音
     * @param voiceFile
     * @return
     */
    public Boolean sendVoice(MultipartFile voiceFile) {
        try {
            //获取用户的登录信息
            User user = UserThreadLocal.get();
            //封装语音对象
            Voice voice=new Voice();
            //主键id
            voice.setId(ObjectId.get());
            voice.setUserId(user.getId());
            //语音文件上传阿里云
            PicUploadResult upload = picUploadService.upload(voiceFile);
            voice.setVoiceUrl(upload.getName());
            String voiceId=voiceApi.saveVoice(voice);
            return StrUtil.isNotEmpty(voiceId);
        } catch (Exception e) {
            log.error("语音上传失败");
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 接收语音
     * @return
     */
    public VoiceVo receiveVoice() {
        //获取当前用户的信息
        User user = UserThreadLocal.get();
        try {
            //获取语音集合
            List<Voice> voiceList=voiceApi.queryVoice(user.getId());
            if(CollUtil.isNotEmpty(voiceList)){
                //随机获取一个语音
                int index = RandomUtil.randomInt(0, voiceList.size());
                Voice voice = voiceList.get(index);
                UserInfo userInfo = userInfoService.queryUserInfoByUserId(voice.getUserId());
                //封装返回前台的实体类
                VoiceVo voiceVo=new VoiceVo();
                voiceVo.setId(voice.getUserId());
                voiceVo.setAge(userInfo.getAge());
                voiceVo.setAvatar(userInfo.getLogo());
                voiceVo.setGender(userInfo.getSex().getValue() == 1 ? "man" : "woman");
                voiceVo.setNickname(userInfo.getNickName());
                voiceVo.setSoundUrl(voice.getVoiceUrl());
                voiceVo.setRemainingTimes(this.getRemainingTimes(user.getId()));
                //将获取过的语音vid存入redis中，避免重复获取
                if(!redisTemplate.hasKey(VOICE_REDIS_KEY_PREFIX+user.getId())){
                    redisTemplate.opsForValue().set(VOICE_REDIS_KEY_PREFIX+user.getId(),String.valueOf(voice.getVid()));
                }else{
                    //已经存在，拼接数据
                    String vids = redisTemplate.opsForValue().get(VOICE_REDIS_KEY_PREFIX + user.getId());
                    vids=vids+","+voice.getVid();
                    redisTemplate.opsForValue().set(VOICE_REDIS_KEY_PREFIX + user.getId(),vids);
                }
                return voiceVo;
            }
        } catch (Exception e) {
            //接收请求失败，把rdis中的次数加回去
            redisTemplate.opsForValue().increment(REMANNING_REDIS_KEY_PREFIX+user.getId(),1);
            log.error("接收语音失败");
            e.printStackTrace();
        }
        return null;

    }

    /**
     * 获取剩余次数
     * @param id
     * @return
     */
    private Integer getRemainingTimes(Long id) {
        String redisKey=REMANNING_REDIS_KEY_PREFIX+id;
        return Convert.toInt(redisTemplate.opsForValue().get(redisKey));
    }
}
